layui.use(['table','form', 'element'], function () {
    let table = layui.table,
        form = layui.form,
        $ = layui.jquery,
       element = layui.element;

    //方法级渲染
    table.render({
        elem: '#admMq'
        , url: '/admMq/page'
        , toolbar: '#toolbarTable'
        , title: '项目'
        , totalRow: true
        , id: "admMq"
        ,skin: 'line'
        ,where: {
            mqType: $('#mqType').val(),
            content: $('#content').val(),
        }
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'mqType', title: '类型', width: 100, sort: true}
            , {field: 'name', title: '名称', width: 280, sort: true}
            , {field: 'ip', title: '安装服务器', width: 140, sort: true}
            , {field: 'port', title: '端口', width: 100, sort: true}
            , {field: 'username', title: '用户名', width: 100, sort: true}
            , {field: 'password', title: '密码', width: 130, sort: true}
            , {field: 'clientUrl', title: '客户端地址', width: 220, sort: true,templet:function(d) {
                    if (d.clientUrl!=null){
                        return '<a style="text-decoration:underline;" target="_blank" href="'+d.clientUrl+'"> '+d.clientUrl+' </a>'
                    }else {
                        return ""
                    }
                }}
            , {field: 'stateName', title: '状态', width: 100, sort: true,templet: function (d) {
                    let className = '';
                    if (d.stateName == 'running'){
                        className = 'layui-bg-green'
                    }if (d.stateName == 'exited') {
                        className = 'layui-bg-red'
                    }if (d.stateName == 'paused') {
                        className = 'layui-bg-warm'
                    }if (d.stateName == '连接失败' ||d.stateName == '未绑定docker' ) {
                        className = 'layui-bg-gray'
                    }
                    return '<span class = "layui-badge '+className+'" >'+d.stateName+'</span>';
                }}
            , {field: 'installTime', title: '安装时间', width: 200, sort: true}
            , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 250}
        ]]
        , even: true
        , page: true //是否显示分页
        , skip: true //开启跳页
        , limits: [10, 30, 60]
        , width: 1700
        // , height: 'full-150'
        , limit: 10 //每页默认显示的数量
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            return {
                "code": status, //解析接口状态   （好像必须是0 才可以）
                "msg": data.desc, //解析提示文本
                "count": data.total, //解析数据长度
                "data": data.records //解析数据列表
            };
        }
        ,done:function (res,currentCount) {
            //***重点***：table渲染完成后渲染element进度条
            element.render()
        }

    });


    //头工具栏事件
    table.on('toolbar(admMq)', function (obj) {
        let data = table.checkStatus(obj.config.id).data;
        let ids = "";
        switch (obj.event) {
            case 'add':
                add();
                break;
            case 'del':
                if (data.length==0){
                    layer.msg("请先勾选数据",{icon:2,time:3000});
                    return;
                }
                for (let i = 0; i < data.length; i++) {
                    ids+=data[i].id+","
                }
                ids = ids.substr(0,ids.length-1);
                del(ids);
                break;
            case 'install':
                if (data.length==0){
                    layer.msg("请先勾选数据",{icon:2,time:3000});
                    return;
                }
                for (let i = 0; i < data.length; i++) {
                    ids+=data[i].id+","
                }
                const dataJson = JSON.stringify(data)
                ids = ids.substr(0,ids.length-1);
                const type = $('#mqType').val()
                if (type == 'rabbitmq'){
                    install_rabbitmq(ids,dataJson);
                }else if (type == 'kafka'){
                    install_kafka(ids,dataJson);
                }
                break;
        }
        ;
    });
    function install_rabbitmq(ids,dataJson) {
        layer.open({
            type: 2,
            title: 'rabbitmq安装',
            area: ['700px', '650px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: false,
            content: ["install_rabbitmq.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                body.find("#dataJson").val(dataJson);
                body.find("#ids").val(ids);

            },
            yes: function () {
            }
        });
    }
    //监听行工具事件
    table.on('tool(admMq)', function (obj) {
        const data = obj.data;
        if (obj.event === 'update'){
            update(data);
        }else if (obj.event === 'del'){
            del(data.id)
        }else if (obj.event === 'ssh'){
            ssh(data)
        }else if (obj.event === 'docker'){
            docker(data)
        }
    });
    function ssh(data) {
        $.ajax({
            type: "get",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/server/getServerById/"+data.serverId,//url
            success: function (result) {
                if (result.code == 0) {
                    let params = {
                        "ip": result.data.ip,
                        "username": result.data.username,
                        "password": result.data.password,
                        "port": result.data.port
                    };
                    window["sshParams"] = params;
                    const newWindow = window.open("../ssh/webssh.html");
                    const loop = setInterval(function () {
                        if (newWindow.closed) {
                            clearInterval(loop);
                        } else {
                            newWindow.document.title = result.data.ip;
                        }
                    }, 1000);
                };
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    function docker(data) {
        $.ajax({
            type: "get",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admDocker/getById/"+data.dockerId,//url
            success: function (result) {
                if (result.code == 0) {
                    window.open(result.data.portainerUrl);
                };
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    function del(ids) {
        layer.confirm("确认要删除吗，删除后不能恢复", { title: "删除确认" }, function (index) {
            $.ajax({
                type: "delete",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "/admMq/"+ids,//url
                success: function (result) {
                    if (result.code == 0) {
                        layer.msg("删除成功",{icon:1,time:1000},function () {
                            location.reload();
                        });
                    };
                },
                error: function () {
                    alert("异常！");
                }
            });
        })
    }

    function add() {
        layer.open({
            type: 2,
            title: '新增mq消息队列',
            area: ['700px', '600px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: false,
            content: ["add.html", 'no'],
            success: function (layero, index) {
                form.render();
            },
            yes: function () {
            }
        });
    }
    function update(data) {
        layer.open({
            type: 2,
            title: '修改mq消息队列',
            area: ['700px', '450px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: false,
            content: ["update.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                body.find("#id").val(data.id);
                body.find("#name").val(data.name);
                body.find("#serverId").val(data.serverId);
                body.find("#mqType").val(data.mqType);
                body.find("#port").val(data.port);
                body.find("#username").val(data.username);
                body.find("#password").val(data.password);
                body.find("#mountPath").val(data.mountPath);
                body.find("#clientUrl").val(data.clientUrl);
                body.find("#dockerId").val(data.dockerId);
                body.find("#containerId").val(data.containerId);
                body.find("#installTime").val(data.installTime);
            },
            yes: function () {
            }
        });
    }

    $('#query').click(function(){
        search();
    });
    $(document).keyup(function(event){
        if(event.keyCode ==13){
            search();
        }
    });
    function search(){
        //执行重载
        table.reloadData('admMq', {
            method: 'get',
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                mqType: $('#mqType').val(),
                content: $('#content').val(),
            }
        }, 'data');
    }
});